# 17.11. 中等：单词距离
import numpy


def finClosest(words, word1, word2):
    index1, index2 = [], []
    for i, word in enumerate(words):
        if word == word1:
            index1.append(i)
        elif word == word2:
            index2.append(i)
    ret = numpy.Inf

    # n^2
    # for i in range(len(index1)):
    #     for j in range(len(index2)):
    #         ret = min(ret, abs(index1[i] - index2[j]))

    #
    # i, j = 0, 0
    # while i < len(index1) and j < len(index2):
    #     ret = min(ret, abs(index1[i] - index2[j]))
    #     if index1[i] > index2[j]:
    #         j += 1
    #     else:
    #         i += 1
    # if i < len(index1):
    #     ret = min(ret, abs(index1[i + 1] - index2[j - 1]))
    # else:
    #     ret = min(ret, abs(index1[i - 1] - index2[j + 1]))
    #
    # return ret

    # 双指针
    ans = len(words)
    index1, index2 = -1, -1
    for i, word in enumerate(words):
        if word == word1:
            index1 = i
        elif word == word2:
            index2 = i
        if index1 >= 0 and index2 >= 0:
            ans = min(ans, abs(index1 - index2))
    return ans


print(finClosest(["I","am","a","student","from","a","university","in","a","city"], "a", "student"))